package com.jzo2o.market.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.market.dto.request.CouponUseBackReqDTO;
import com.jzo2o.api.market.dto.request.CouponUseReqDTO;
import com.jzo2o.api.market.dto.response.AvailableCouponsResDTO;
import com.jzo2o.api.market.dto.response.CouponUseResDTO;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.common.expcetions.DBException;
import com.jzo2o.common.model.CurrentUser;
import com.jzo2o.common.utils.*;
import com.jzo2o.market.enums.ActivityStatusEnum;
import com.jzo2o.market.enums.CouponStatusEnum;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.market.mapper.CouponMapper;
import com.jzo2o.market.model.domain.Coupon;
import com.jzo2o.market.model.dto.request.CouponOperationPageQueryReqDTO;
import com.jzo2o.market.model.dto.response.CouponInfoResDTO;
import com.jzo2o.market.service.IActivityService;
import com.jzo2o.market.service.ICouponService;
import com.jzo2o.market.service.ICouponUseBackService;
import com.jzo2o.market.service.ICouponWriteOffService;
import com.jzo2o.mysql.utils.PageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-09-16
 */
@Service
@Slf4j
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements ICouponService {

    @Resource(name = "seizeCouponScript")
    private DefaultRedisScript<String> seizeCouponScript;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private IActivityService activityService;

    @Resource
    private ICouponUseBackService couponUseBackService;

    @Resource
    private ICouponWriteOffService couponWriteOffService;
    @Resource
    private  ICouponService couponService;



    @Override
    public List<CouponInfoResDTO> myCoupon(Integer status,Long lastId) {
        // 1.获取用户id
        CurrentUser currentUser = UserContext.getCurrentUser();
        Long userId = currentUser.getId();
        if (userId == null){
            throw new BadRequestException("用户登录信息有误");
        }

        // 根据用户Id和状态查询优惠券，查询已领取的优惠券，按领取优惠券的时间降序显示。
        List<Coupon> coupons = lambdaQuery()
                .eq(Coupon::getUserId, userId)
                .eq(Coupon::getStatus, status)
                .lt(ObjectUtils.isNotEmpty(lastId), Coupon::getId, lastId)
                .orderByDesc(Coupon::getCreateTime)
                .last("LIMIT 10").list();

        return CollUtils.isEmpty(coupons) ? new ArrayList<>() : coupons.stream().map(coupon -> BeanUtils.toBean(coupon, CouponInfoResDTO.class))
.collect(Collectors.toList());

    }

    @Override
    public List<AvailableCouponsResDTO> getAvailable(Long userId, BigDecimal totalAmount) {
        List<Coupon> list = lambdaQuery()
               .eq(Coupon::getUserId, userId)
               .le(Coupon::getAmountCondition, totalAmount)
                .le(Coupon::getDiscountAmount, totalAmount)
              .eq(Coupon::getStatus, CouponStatusEnum.NO_USE)
            .ge(Coupon::getValidityTime, LocalDateTime.now())
             .list();
        if (list.isEmpty()){
            return new ArrayList<>();
        }
        return list.stream().map(coupon ->BeanUtils.toBean(coupon,AvailableCouponsResDTO.class))
                .sorted(Comparator.comparing(AvailableCouponsResDTO::getDiscountAmount)).collect(Collectors.toList());

    }

    @Resource
    private CouponMapper couponMapper;

    /**
     * 查询领取记录
     */
    @Override
    public PageResult<CouponInfoResDTO> page(CouponOperationPageQueryReqDTO couponOperationPageQueryReqDTO) {

        LambdaQueryWrapper<Coupon> queryWrapper = new LambdaQueryWrapper<>();

        if (couponOperationPageQueryReqDTO.getActivityId() != null) {
            queryWrapper.eq(Coupon::getActivityId, couponOperationPageQueryReqDTO.getActivityId());
        }

        //列表内数据倒序进行展示；
        queryWrapper.orderByDesc(Coupon::getCreateTime);

        Page<Coupon> couponInfoResDTOPage = PageUtils.parsePageQuery(couponOperationPageQueryReqDTO, Coupon.class);
        Page<Coupon> couponPage = baseMapper.selectPage(couponInfoResDTOPage, queryWrapper);
        return PageUtils.toPage(couponPage, CouponInfoResDTO.class);
    }

}
